package cn.topcodes.tcsf.admin.web.controller.impl;

import cn.topcode.unicorn.utils.ValidationUtil;
import cn.topcodes.tcsf.admin.commons.api.security.ShiroUtil;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.admin.commons.api.controller.generic.GenericApiController;
import cn.topcodes.tcsf.admin.domain.entity.SysMenu;
import cn.topcodes.tcsf.admin.domain.entity.SysUser;
import cn.topcodes.tcsf.admin.domain.form.NestableSort;
import cn.topcodes.tcsf.admin.domain.form.SysMenuForm;
import cn.topcodes.tcsf.admin.domain.view.SysMenuVo;
import cn.topcodes.tcsf.admin.service.res.SysMenuService;
import cn.topcodes.tcsf.admin.service.org.SysUserService;
import cn.topcodes.tcsf.admin.web.controller.SysMenuApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.EntityNotFoundException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/admin/sys-menu")
public class SysMenuApiController extends GenericApiController<SysMenu, SysMenuVo, SysMenuForm> implements SysMenuApi {

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysMenuService sysMenuService;
	
	@RequestMapping("")
	public String index() {
		return "admin/sys-menu";
	}

	@Override
	public ApiResponseEntity<Void> update(
			HttpServletRequest request,
			@Valid SysMenuForm form, BindingResult result) {
		ValidationUtil.validate(result);
		SysMenu menu = this.form2Entity(form);
		SysMenu entity = this.getService().findOne(form.getId());
		if(entity == null)
			throw new EntityNotFoundException("无法修改！菜单不存在");
		menu.setParentId(entity.getParentId());
		menu.setSort(entity.getSort());
		this.getService().update(menu);
		return ApiResponseEntity.buildOK();
	}

	@Override
	protected boolean validateOperation(String password) {
		Long userId = ShiroUtil.getUserId();
		SysUser user = this.sysUserService.findOne(userId);
		if(user == null) {
			throw new EntityNotFoundException("管理用户不存在");
		}
		return this.sysUserService.isPwdEqual(password,user);
	}

	@ResponseBody
	@RequestMapping(value = "save-sort",method = RequestMethod.POST)
	public ApiResponseEntity saveSort(@RequestBody(required = true) List<NestableSort> sort) {
		this.sysMenuService.saveSort(sort);
		return ApiResponseEntity.buildOK();
	}
}
